<?php 

 // if(!define('BASEPATH')) exit('No direct script access allowed');

 /*
 	* phan quan tri website
 	* 
 */

 class Admin extends CI_Controller 
 {
 	// dinh nghia vai gia tri
 	var $template;
 	var $template_path;
 	// link web
 	var $website_link;

	public function __construct()
	{
		parent::__construct();		

		// dinh nghia duong dan admin, giao dien admin
		$this->template = 'thegioihandmade/admin/';
		$this->template_path = 'template/reponsive/admin/';

		// link web
		$this->website_link = '
			<li><a href="'.site_url('admin/newCategory').'">Quản lý danh mục</a></li>
			<li><a href="'.site_url('admin/products').'">Quản lý sản phẩm</a></li>
			<li><a href="'.site_url('admin/ads').'">Quản lý slide</a></li>
			<li><a href="'.site_url('admin/settings').'">Cài đặt</a></li>
		';

		//goi model san pham, danh muc, quang cao

		$this->load->model('Category');

		$this->load->model('Product');	

		$this->load->model('Ad');

		$this->load->model('Position');

		$this->load->model('Setting');

		$this->load->model('News');

		$this->load->model('NewsCategory');

		$this->load->model('Page');

		$this->load->model('Support');

		$this->load->model('User');

		//phân trang

		$this->load->library('pagination');
	}

	

	function showHeader()
	{
		// khai bao du lieu duong dan giao dien
		$data['template'] = $this->template;
		$data['template_path'] = $this->template_path;

		//check login first

		$logged_in = $this->session->userdata('logged_in');

		if(isset($logged_in) && !empty($logged_in))
		{

			$session_data = $this->session->userdata('logged_in');

		    $data['username'] = $session_data['username'];   

		    $this->load->view($this->template.'header',$data);
		}
		else
		{
			redirect('admin/show_login');			
		}
	}



	public function index($category_id = false, $paging = false)
	{
		$this->showHeader();

		$data['template'] = $this->template;
		$data['template_path'] = $this->template_path;
		
		// notify
		$notify = $this->session->userdata('notify');
		if( !empty($notify) )
		{
			$data['notify'] = $notify;
			$this->session->unset_userdata('notify');
		}

		// menu
		$data['website_link'] = $this->website_link;

		//lay thong tin roi show ra day
		//$toppage_data = $this->getAdminTopPageData();		
		
		// danh muc		
		$data['categories'] = $this->Category->getAllCategories();

		//san pham
		$limit = 10;
		$data['products'] = $this->Product->getAllProducts($category_id,$paging,$limit);					
		
		//start paging products
		$total_rows = $this->Product->count_all_results();

		if( !$category_id )
		{
			$config['base_url'] = site_url('admin/index/false');	
		}
		else
		{
			$config['base_url'] = site_url('admin/index/'.$category_id);
		}
		

		$config['total_rows'] = $total_rows;

		$config['per_page'] = $limit; 
		
		$config['uri_segment'] = 4;				

		$this->pagination->initialize($config); 		
		
		$data['products_paging'] = $this->pagination->create_links();
		// end paging

		if( empty($data['products']) )
		{
			$this->session->set_userdata('notify','Chưa có sản phẩm');
		}

		$this->load->view($this->template.'toppage',$data);				

		//ket thuc body
		$this->load->view($this->template.'footer');
	}



	/************************************************************************

	 *

	 * Product

	 * Product section for Admin 

	 *

	 * Function products

	 * Function newProduct

	 * Function editProduct

	 * Function deleteProduct

	 *

	************************************************************************/

	
	/* function is commented as unused.
	public function products($num_of_products = false)
	{

		$this->showHeader();

		//lay danh sach san pham show ra

		$data['categories'] = $this->Category->getAllCategories();

		//display products

		$data['products'] = $this->Product->getAllProducts($num_of_products);

		//paging products

		$config['base_url'] = site_url('admin/products');

		$config['total_rows'] = 200;

		$config['per_page'] = 5; 

		$this->pagination->initialize($config); 



		$data['products_paging'] = $this->pagination->create_links();

		//end paging

		$this->load->view('admin/products',$data);

		//lay danh sach danh muc show ra

		$this->load->view('admin/footer');

	}
	*/


	public function newProduct()
	{		
		//if form is submitted then redirect to homepage

		if(isset($_POST['submitBtn']) && !empty($_POST['submitBtn']))
		{						
			//upload image 

			//create thumb 300x273

			//create thumbnail 360x300 [view detail]

			// create thumbnail slide 101x84 [view detail]

			// create thumbnail slide 150x100 [other products]

			//create image 250x250

			//if susccess return image and thumbnail

			$data = $this->getProductImage2('image');



			$thumb = $data['resize']['thumb'];

			$image = $data['resize']['image'];	

			$thumbnail = $data['resize']['thumbnail'];

			$thumb_slide = $data['resize']['thumb_slide'];

			$thumb_slide2 = $data['resize']['thumb_slide2'];



			//adding more image

			$image1 = $this->getProductImage('image1',1);

			$image2 = $this->getProductImage('image2',1);

			$image3 = $this->getProductImage('image3',1);

			$image4 = $this->getProductImage('image4',1);

			//price

			//add fix patch for converting price to VND

			$price_origin = $this->input->post('price');

			$price = $price_origin;

			//$price = number_format($price_origin,0,",",".");

			//date added

			$created_date = date('yyyy-mm-dd H:i:s',strtotime('now'));				



			$data = array(

					'name' 	         => $this->input->post('name'),

					'desc'			 => $this->input->post('desc'),

					'price'          => $price,

					'price_add'		 => $price_origin,

					'thumb'			 => $thumb,

					'thumbnail'		 => $thumbnail,

					'thumb_slide'	 =>	$thumb_slide,

					'thumb_slide2'	 =>	$thumb_slide2,

					'image'			 => $image,

					//further settings					

					'quantity' 	     => $this->getProductFieldValue(false,'quantity'),

					'origin'		 => $this->input->post('origin'),

					'warranty'		 => $this->input->post('warranty'),

					'status'		 => $this->input->post('status'),

					'modified_date'	 => $created_date,

					'created_date'	 => $created_date,

					'detail'		 => $this->input->post('detail'),

					'product_relate' => $this->input->post('product_relate'),

					'category_id'	 => $this->input->post('category_id'),

					//adding image

					'image1'		 => $image1['upload_data']['file_name'],

					'image2'		 => $image2['upload_data']['file_name'],

					'image3'		 => $image3['upload_data']['file_name'],

					'image4'		 => $image4['upload_data']['file_name'],	

					//adding thumb image 

					'image1_thumb'	 => $this->createThumbImage($image1),

					'image2_thumb'	 => $this->createThumbImage($image2),

					'image3_thumb'	 => $this->createThumbImage($image3),

					'image4_thumb'	 => $this->createThumbImage($image4),

				);			
			

			//add 6 product for category

			$i = 1;

			//while($i < 10)

			//{

				$this->Product->addNewProduct($data);

			//	$i++;	

			//}

			$this->session->set_userdata('notify','Sản phẩm '.$data['name'].' đã được tạo thành công !');
			//$this->session->set_userdata('notify',$this->db->last_query());

			redirect('admin/index','refresh');			

		}
		else
		{			
			$this->showHeader();

			$data['categories'] = $this->Category->getAllCategories();

			$this->load->view($this->template.'newproduct',$data);

			$this->load->view($this->template.'footer');
		}				

	}



	public function resizeImage($path = false)
	{

		//load library

		$this->load->library('image_lib');



		//auto resize 120px x 120px

		$config['image_library'] = 'gd2';

		$config['source_image']	= $path;

		$config['create_thumb'] = TRUE;

		$config['maintain_ratio'] = TRUE;

		$config['width']	 = 120;

		$config['height']	= 120;



		$this->load->library('image_lib', $config); 



		$this->image_lib->resize();

	}



	public function editProduct($id)
	{			
		//if id is empty then redirect to product page

		if($id == FALSE)
		{
			redirect('admin/index','refresh');
		}
		else
		{
			$product = $this->Product->getProduct($id);

			if(!isset($product) || empty($product))
			{
				redirect('admin/index','refresh');
			}			
		}

		//if submit button is pressed, then process updating product

		if(isset($_POST['submitBtn']) && !empty($_POST['submitBtn']) )
		{
			//thumbnail

			$thumbnail_upload = $this->getProductImage('thumbnail');

			//process image first

			$image_upload_result = $this->getProductImage();

			//image 1

			$image1_upload = $this->getProductImage('image1');

			//image 2

			$image2_upload = $this->getProductImage('image2');

			//image 3

			$image3_upload = $this->getProductImage('image3');

			//image 4

			$image4_upload = $this->getProductImage('image4');



			//manually

			if(!isset($image_upload_result['error']) && empty($image_upload_result['error']))
			{
				if(isset($product['image']) && !empty($product['image']))
				{
					$image_field_value = $product['image'];
				}
				else
				{
					$image_field_value = $image_upload_result['upload_data']['file_name'];
				}				
			}
			else
			{
				$image_field_value = $product['image'];
			}

			//thumbnail

			if(!isset($thumbnail_upload['error']) && empty($thumbnail_upload['error']))
			{
				if(isset($product['thumbnail']) && !empty($product['thumbnail']))
				{
					$thumbnail = $product['thumbnail'];
				}
				else
				{
					$thumbnail = $thumbnail_upload['upload_data']['file_name'];
				}					
			}
			else
			{
				$thumbnail = $product['thumbnail'];
			}

			//image 1
			if(!isset($image1_upload['error']) && empty($image1_upload['error']))
			{
				if(isset($product['image1']) && !empty($product['image1']))
				{
					$image1 = $product['image1'];
				}
				else
				{
					$image1 = $image1_upload['upload_data']['file_name'];
				}					
			}
			else
			{
				$image1 = $product['image1'];
			}

			//image 2

			if(!isset($image2_upload['error']) && empty($image2_upload['error']))
			{
				if(isset($product['image2']) && !empty($product['image2']))
				{
					$image2 = $product['image2'];
				}
				else
				{
					$image2 = $image2_upload['upload_data']['file_name'];
				}					
			}
			else
			{
				$image2 = $product['image2'];
			}

			//image 3
			if(!isset($image3_upload['error']) && empty($image3_upload['error']))
			{
				/*
				if(isset($product['image3']) && !empty($product['image3']))
				{
					$image3 = $product['image3'];
				}
				*/
				//else
				{
					$image3 = $image3_upload['upload_data']['file_name'];
				}					
			}
			else
			{
				$image3 = $product['image3'];
			}

			//image 4
			if(!isset($image4_upload['error']) && empty($image4_upload['error']))
			{				
				/*
				if(isset($product['image4']) && !empty($product['image4']))
				{
					$image4 = $product['image4'];
				}
				*/
				//else
				{
					$image4 = $image4_upload['upload_data']['file_name'];
				}					
			}
			else
			{
				$image4 = $product['image4'];
			}



			//price
			$origin_price = $this->input->post('price');

			$price_input = number_format($origin_price,0,",",".");

			$data = array(

					'name' 	         => $this->getProductFieldValue($product,'name'),

					'desc'			 =>	$this->getProductFieldValue($product,'desc'),

					'price'          => $origin_price,

					'price_add'		 => $origin_price,

					// 'thumb'			 => $this->createThumbImage($image_upload_result),

					// 'thumbnail'		 => $thumbnail,

					// 'image'			 => $image_field_value,

					//further settings					

					'quantity' 	     => $this->getProductFieldValue($product,'quantity'),

					'origin'		 => $this->getProductFieldValue($product,'origin'),

					'warranty'		 => $this->getProductFieldValue($product,'warranty'),

					'status'		 => $this->getProductFieldValue($product,'status'),

					'modified_date'	 => date('d/m/Y',strtotime('now')),					

					'detail'		 => $this->getProductFieldValue($product,'detail'),

					'product_relate' => $this->getProductFieldValue($product,'product_relate'),

					'category_id'	 => $this->getProductFieldValue($product,'category_id'),

					//adding image

					// 'image1'		 => $image1,

					// 'image2'		 => $image2,

					// 'image3'		 => $image3,

					// 'image4'		 => $image4,	

					//thumb image

					// 'image1_thumb'	 => $this->createThumbImage($image1_upload),

					// 'image2_thumb'	 => $this->createThumbImage($image2_upload),

					// 'image3_thumb'	 => $this->createThumbImage($image3_upload),

					// 'image4_thumb'	 => $this->createThumbImage($image4_upload),

				);	

			$this->Product->editProduct($data,$id);						
			
			$this->session->set_userdata('notify','Sản phẩm '.$data['name'].' cập nhật thành công !');

			redirect('admin/index');
		}	
		//otherwise show product need to edit					
		else
		{

			$data['categories'] = $this->Category->getAllCategories();

			$data['product'] = $product;

			$this->showHeader();

			$this->load->view($this->template.'editproduct',$data);

			$this->load->view($this->template.'footer');
		}

	}


	public function deleteProduct($id)
	{
		$product = $this->Product->getProduct($id);

		if(!empty($product))
		{
			$this->Product->deleteProduct($id);

			$this->session->set_userdata('notify','Sản phẩm đã xóa!');

			redirect('admin/index','refresh');
		}
	}


	function getProductImage($imageField = false,$debug = false)
	{

		if($imageField == false)

		{

			$imageField = 'image';

		}

		//if product image is uploaded, then replace current image with new image

		$input_image = $this->input->post($imageField);



		if(!isset($input_image) && empty($input_image))

		{

			$data['upload_data']['file_name'] = 'no_image.jpg';
			$data['error'] = 'yes';
		}

		else

		{

			$config['upload_path'] = './upload/image/products';

			$config['allowed_types'] = 'gif|jpg|png';

			$config['max_size']	= '5000';

			$config['max_width']  = '10240';

			$config['max_height']  = '7680';



			$this->load->library('upload', $config);



			if ( ! $this->upload->do_upload($imageField))

			{

				//$data = array('error' => $this->upload->display_errors());	

				$data['upload_data']['file_name'] = 'no_image.jpg';			

			}

			else

			{

				/*

				$file_name = $data['upload_data']['raw_name'];

				$file_type = $data['upload_data']['file_ext'];

				$type = 'origin';

				$this->resize_image($file_name,$file_type,$type);

				*/

				$data = array('upload_data' => $this->upload->data());			

			}

		}				

		

		return $data;

	}



	function createThumbImage($data = false)
	{

		if($data == false)

		{

			redirect('admin/products','refresh');			

		}



		if($data['upload_data']['file_name'] == 'no_image.jpg')

		{

			return 'thum_no_image.jpg';

		}

		else

		{

			//resize with image name + '40x40' + '.jpg'

			$file_name = $data['upload_data']['raw_name'];

			$file_type = $data['upload_data']['file_ext'];

			$type 	   = 'thumb_slide';

			$this->resize_image($file_name,$file_type,$type);

			return $file_name.'101x84'.$file_type;

		}

	}



	function getProductImage2($imageField = false,$debug = false)
	{

		if($imageField == false)

		{

			$imageField = 'image';

		}

		//if product image is uploaded, then replace current image with new image

		$input_image = $this->input->post($imageField);



		if(!isset($input_image) && empty($input_image))
		{

			$data['resize']['image'] = 'no_image.jpg';

			$data['resize']['thumbnail'] = 'thumbnail_no_image.jpg';

			$data['resize']['thumb'] 	= 'thum_no_image.jpg';

			$data['resize']['thumb_slide'] 	= 'thum_no_image.jpg';

			$data['resize']['thumb_slide2'] 	= 'thum_no_image.jpg';
		}
		else
		{

			$config['upload_path'] = './upload/image/products';

			$config['allowed_types'] = 'gif|jpg|png';

			$config['max_size']	= '5000';

			$config['max_width']  = '10240';

			$config['max_height']  = '7680';



			$this->load->library('upload', $config);



			if ( ! $this->upload->do_upload($imageField))
			{

				//$data = array('error' => $this->upload->display_errors());	

				$data['resize']['image'] = 'no_image.jpg';

				$data['resize']['thumbnail'] = 'thumbnail_no_image.jpg';

				$data['resize']['thumb'] 	= 'thum_no_image.jpg';

				$data['resize']['thumb_slide'] 	= 'thum_no_image.jpg';

				$data['resize']['thumb_slide2'] 	= 'thum_no_image.jpg';				
			}
			else
			{
				$data = array('upload_data' => $this->upload->data());	

				//creat thumb 300x273

				$this->resize_image($data['upload_data']['raw_name'],$data['upload_data']['file_ext'],'thumb');

				//create thumbnail 360x300				

				$this->resize_image($data['upload_data']['raw_name'],$data['upload_data']['file_ext'],'thumbnail');

				//create image 250x250px				

				$this->resize_image($data['upload_data']['raw_name'],$data['upload_data']['file_ext'],'image');

				//create thumbnail slide 101x84			

				$this->resize_image($data['upload_data']['raw_name'],$data['upload_data']['file_ext'],'thumb_slide');

				// create thumbnail slide 150x100 [other product]

				$this->resize_image($data['upload_data']['raw_name'],$data['upload_data']['file_ext'],'thumb_slide2');					

				$data = array(

					'resize' => array(

							'thumb' => $data['upload_data']['raw_name'].'300x273'.$data['upload_data']['file_ext'],

							'image' => $data['upload_data']['raw_name'].'250x250'.$data['upload_data']['file_ext'],

							'thumbnail' => $data['upload_data']['raw_name'].'360x300'.$data['upload_data']['file_ext'],

							'thumb_slide' => $data['upload_data']['raw_name'].'101x84'.$data['upload_data']['file_ext'],

							'thumb_slide2' => $data['upload_data']['raw_name'].'150x100'.$data['upload_data']['file_ext'],
						)

					);

			}

		}				

		

		return $data;

	}





	function resize_image($file_name = false,$file_type = false,$type = false)
	{

		$config['image_library'] = 'gd2';

		$config['source_image']	= './upload/image/products/'.$file_name.$file_type;

		if($type == 'thumb')
		{
			$config['new_image']    = './upload/image/products/'.$file_name.'300x273'.$file_type;
		}

		if($type == 'thumbnail')
		{
			$config['new_image']    = './upload/image/products/'.$file_name.'360x300'.$file_type;
		}
		else if($type == 'image')
		{
			$config['new_image']    = './upload/image/products/'.$file_name.'250x250'.$file_type;
		}		
		else if($type == 'thumb_slide')
		{
			$config['new_image']    = './upload/image/products/'.$file_name.'101x84'.$file_type;
		}
		else if($type == 'thumb_slide2')
		{
			$config['new_image']    = './upload/image/products/'.$file_name.'150x100'.$file_type;
		}
		else if($type == 'slide')
		{
			// redeclare source_image as different path [ad]
			$config['source_image']	= './upload/image/ads/'.$file_name.$file_type;
			$config['new_image']    = './upload/image/ads/'.$file_name.'1680x600'.$file_type;
		}
		else if($type == 'logo')
		{
			// redeclare source_image as different path [logo]
			$config['source_image']	= './upload/image/settings/'.$file_name.$file_type;
			$config['new_image']    = './upload/image/settings/'.$file_name.'181x41'.$file_type;	
		}
		else if($type == 'origin')
		{
			$config['new_image']    = './upload/image/products/'.$file_name.$file_type;
		}		

		$config['create_thumb'] = FALSE;

		$config['maintain_ratio'] = TRUE;

		if($type == 'thumb')
		{
			$config['width']	 = 300;

			$config['height']	= 273;
		}
		if($type == 'thumbnail')
		{
			$config['width']	 = 360;

			$config['height']	= 300;
		}
		else if($type == 'image')
		{
			$config['width']	 = 420;

			$config['height']	= 420;
		}
		else if($type == 'thumb_slide')
		{
			$config['width']	 = 101;

			$config['height']	= 84;	
		}
		else if($type == 'thumb_slide2')
		{
			$config['width']	 = 150;

			$config['height']	= 100;	
		}
		else if($type == 'slide')
		{
			$config['width'] = 1680;

			$config['height'] = 600;
		}
		else if($type == 'logo')
		{
			$config['width'] = 181;
			$config['height'] = 41;
		}
		else if($type == 'origin')
		{
			$config['width']	 = 400;

			$config['height']	= 420;	
		}		


		$this->load->library('image_lib', $config);



		//path fix add multiple images 

		$this->image_lib->clear();

		$this->image_lib->initialize($config); 



		$this->image_lib->resize();

	}



	function getProductFieldValue($productData = false,$fieldName = false,$id = false)
	{

		$fieldValue = $this->input->post($fieldName);		

		if(isset($fieldValue) && !empty($fieldValue))

		{

			return $fieldValue;

		}

		else

		{			

			if($productData != false)

			{

				return $productData[$fieldName];

			}

			else

			{

				return 1;	

			}				

		}

	}



	/************************************************************************

	 * End Product section

	************************************************************************/

		

	/************************************************************************

	 *

	 * Category

	 * Category section for Admin 

	 *

	 * Function newCategory

	 * add new category

	 * Function editCategory

	 * 

	************************************************************************/

		
	public function categories()
	{
		
		$notify = $this->session->userdata('notify');

		if( !empty($notify) )
		{
			$data['notify'] = $notify;
			$this->session->unset_userdata('notify');		
		}		

		$data['categories'] = $this->Category->getAllCategories();	// get all categories to show on page							

		$this->showHeader();

		$this->load->view($this->template.'categories',$data);

		$this->load->view($this->template.'footer');		
	}	

	//add new category	
	public function newCategory()
	{		

		//if form is submitted then redirect to homepage

		if(isset($_POST['submitBtn']) && !empty($_POST['submitBtn']))
		{			

			$data = array(

					'category' 	   => $this->input->post('category'),

					'sub_category' => $this->input->post('sub_category'),

					'active'	   => 1,

				);			

			$this->Category->addCategory($data);

			redirect('admin/newCategory','refresh');

		}
		else
		{			
			$this->showHeader();

			$data['categories'] = $this->Category->getAllCategories1();

			$this->load->view($this->template.'newcategory',$data);

			$this->load->view($this->template.'footer');
		}		

	}



	// Edit category
	public function editCategory($id = false)
	{		

		if($id == false)
		{
			redirect('admin/categories','refresh');
		}
		else
		{
			$category = $this->Category->getCategory($id);


			if(isset($category) && !empty($category))
			{

				//edit button is pressed

				if(isset($_POST['submitBtn']) && !empty($_POST['submitBtn']))
				{

					$data = array(

							'category'		=>	$this->getCategoryFieldValue($category,'category'),

							'sub_category'	=>	$this->getCategoryFieldValue($category,'sub_category'),

						);

					$this->Category->updateCategory($data,$id);

					redirect('admin/categories','refresh');
				}	
				else
				{

					$data['category'] = $category;

					$data['categories'] = $this->Category->getAllCategories();

					$this->showHeader();

					$this->load->view($this->template.'editcategory',$data);

					$this->load->view($this->template.'footer');
				}			
			}
			else
			{
				redirect('admin/categories','refresh');
			}
		}
	}



	//show products of category

	public function showProductsOfCategory($id = false,$num_of_products = false)

	{		

		//if id is not defined, then redirect to homepage

		if($id == false)

		{

			//error notify 

			redirect('admin/index','refresh');

		}

		//products

		$data['products'] = $this->Category->showProductsOfCategory($id,$num_of_products);

		//paging products

		$config['base_url'] = site_url('admin/showProductsOfCategory/'.$id.'/');

		$config['total_rows'] = 200;

		$config['per_page'] = 5; 

		$config['uri_segment'] = 4;

		$config['use_page_numbers'] = TRUE;		



		$this->pagination->initialize($config); 

		$data['products_paging'] = $this->pagination->create_links();

		//end paging products

		$data['categories'] = $this->Category->getAllCategories();



		$this->showHeader();

		$this->load->view('admin/products',$data);

		$this->load->view('admin/footer');

	}



	function getCategoryFieldValue($categoryData = false,$fieldName = false,$id = false)

	{

		$fieldValue = $this->input->post($fieldName);		

		if(isset($fieldValue) && !empty($fieldValue))

		{

			return $fieldValue;

		}

		else

		{			

			if($categoryData != false)

			{

				return $categoryData[$fieldName];

			}

			else

			{

				return 1;	

			}				

		}

	}



	/************************************************************************

	 * End Category section

	************************************************************************/



	/************************************************************************

	 * Advertisement section

	************************************************************************/



	public function ads($pos = false)
	{
		
		$notify = $this->session->userdata('notify');

		if( !empty($notify) )
		{
			$data['notify'] = $notify;
			$this->session->unset_userdata('notify');		
		}		

		$data['ads'] = $this->Ad->getAllAds();	// get all ads to show on page							

		$this->showHeader();

		$this->load->view($this->template.'ads',$data);

		$this->load->view($this->template.'footer');		
	}



	function addNewAd()
	{

		//if Ad is processed then we do submit

		if(isset($_POST['submitBtn']) && !empty($_POST['submitBtn']))
		{

			$image_data = $this->getAdImage();

			//$image_input = $image_data['upload_data']['file_name'];
			$image_input = $image_data['resize']['slide'];

			$data = array(

					'title' => $this->getAdFieldValue('title'),

					'href'	=> $this->getAdFieldValue('href'),

					'image' => $image_input,

					'order' => $this->getAdFieldValue('order'),

					'position_id' => $this->getAdFieldValue('position_id'),

				);

			$this->Ad->addNewAd($data);

			redirect('admin/ads','refresh');
		}
		else
		{
			$data['positions'] = $this->Position->getAll();

			$this->showHeader();

			$this->load->view($this->template.'addNewAd',$data);

			$this->load->view($this->template.'footer');
		}		
	}



	function editAd($id = false)
	{

		if($id == false)
		{
			redirect('admin/ads','refresh');			
		}



		$ad = $this->Ad->getAd($id);



		if(isset($_POST['submitBtn']) && !empty($_POST['submitBtn']))
		{

			$image = $this->getAdImage();

			if( (isset($image['error']) && !empty($image['error'])) || !$image ) 
			{
				$image_input = $ad['image'];
			}
			else
			{
				$image_input = $image['resize']['slide'];
			}

			$data = array(

					'title' => $this->getAdFieldValue('title',$ad),

					'href'	=> $this->getAdFieldValue('href',$ad),

					'image' => $image_input,

					'order' => $this->getAdFieldValue('order',$ad),

					'position_id' => $this->getAdFieldValue('position_id',$ad),

				);



			$this->Ad->updateAd($data,$id);			

			$this->session->set_userdata('notify','Quảng cáo cập nhật thành công !');

			redirect('admin/ads','refresh');						
		}
		else
		{

			$data['ad'] = $ad;

			$data['positions'] = $this->Position->getAll();

			$this->showHeader();

			$this->load->view($this->template.'editAd',$data);

			$this->load->view($this->template.'footer');
		}
	}



	function getAdFieldValue($fieldName = false, $adData = false)
	{

		$fieldValue = $this->input->post($fieldName);

		if(isset($fieldValue) && !empty($fieldValue))
		{
			return $fieldValue;
		}
		else
		{
			if($adData)
			{
				return $adData[$fieldName];
			}
			else
			{
				return 1;
			}
		}
	}

	// remove selected ad
	function deleteAd($id = false)
	{
		$ad = $this->Ad->getAd($id);

		if(!empty($ad))
		{
			if( $this->Ad->deleteAd($id) )
			{
				$this->session->set_userdata('Quảng cáo xóa thành công !');
			}
			redirect('admin/ads','refresh');
		}
	}


	function getAdImage($id = false)
	{

		//if product image is uploaded, then replace current image with new image
		$input_image = $this->input->post('image');



		if(!isset($input_image) && empty($input_image))
		{
			return false;
		}

				

		$config['upload_path'] = './upload/image/ads';

		$config['allowed_types'] = 'gif|jpg|png';

		$config['max_size']	= '5000';

		$config['max_width']  = '10240';

		$config['max_height']  = '7680';



		$this->load->library('upload', $config);



		if ( ! $this->upload->do_upload('image'))
		{
			$data = array('error' => $this->upload->display_errors());							
		}
		else
		{
			$data = array('upload_data' => $this->upload->data());	

			//create slide 1680x600 px
			$this->resize_image($data['upload_data']['raw_name'],$data['upload_data']['file_ext'],'slide');

			$data = array(

					'resize' => array(							

							'slide' => $data['upload_data']['raw_name'].'1680x600'.$data['upload_data']['file_ext'],
						)

					);
		}

		return $data;
	}



	/************************************************************************

	 * End Advertisement section

	************************************************************************/



	/************************************************************************

	 * Settings section

	************************************************************************/



	public function settings()
	{

		$data['settings'] = $this->Setting->getCompany();

		$this->showHeader();

		$this->load->view($this->template.'settings',$data);

		$this->load->view($this->template.'footer');
	}

	// event
	public function event()
	{
		$data['event'] = $this->Page->getPage(6);	// Event page

		$this->showHeader();

		if(isset($_POST['submitBtn']) && !empty($_POST['submitBtn']))
		{						
			$data = array(
					'content' => $this->getSettingFieldValue('content',$data['event']),					
				);

			$this->Page->updatePage($data,6);

			redirect('admin/event','refresh');
		}

		$this->load->view($this->template.'event',$data);

		$this->load->view($this->template.'footer');
	}

	function editSetting($id = false)
	{
		// if($id == false)
		// {
		// 	redirect('admin/index','refresh');
		// }


		$data['settings'] = $this->Setting->getCompany($id);


		if(isset($_POST['submitBtn']) && !empty($_POST['submitBtn']))
		{

			$image = $this->getSettingImage();

			$id = $this->input->post('id');

			if(isset($image['error']) && !empty($image['error']))
			{

				$image_input = $data['settings']['map'];
			}
			else
			{
				$image_input = $image['upload_data']['file_name'];
			}

			$logo = $this->getLogoImage();


			$data = array(

					'company' => $this->getSettingFieldValue('company',$data['settings']),

					'website' => $this->getSettingFieldValue('website',$data['settings']),

					'description' => $this->getSettingFieldValue('description',$data['settings']),

					'address' => $this->getSettingFieldValue('address',$data['settings']),

					'contact' => $this->getSettingFieldValue('contact',$data['settings']),

					'email'  => $this->getSettingFieldValue('email',$data['settings']),					

					'map' => $image_input,

					'logo' => $logo['resize']['logo'],

				);

			$this->Setting->updateSetting($data,$id);

			redirect('admin/settings','refresh');
		}
		else
		{
			$this->showHeader();

			$this->load->view($this->template.'settings',$data);

			$this->load->view($this->template.'footer');
		}
	}

	// get logo image 
	function getLogoImage($id = false)
	{

		//if product image is uploaded, then replace current image with new image
		$input_image = $this->input->post('image');



		if(!isset($input_image) && empty($input_image))
		{
			return false;
		}

				

		$config['upload_path'] = './upload/image/settings';

		$config['allowed_types'] = 'gif|jpg|png';

		$config['max_size']	= '5000';

		$config['max_width']  = '10240';

		$config['max_height']  = '7680';



		$this->load->library('upload', $config);



		if ( ! $this->upload->do_upload('image'))
		{
			$data = array('error' => $this->upload->display_errors());							
		}
		else
		{
			$data = array('upload_data' => $this->upload->data());	

			//create thumbnail 181x41 px
			$this->resize_image($data['upload_data']['raw_name'],$data['upload_data']['file_ext'],'logo');

			$data = array(

					'resize' => array(							

							'logo' => $data['upload_data']['raw_name'].'181x41'.$data['upload_data']['file_ext'],
						)

					);
		}

		return $data;
	}


	function getSettingFieldValue($fieldName = false, $settingData = false)

	{

		$fieldValue = $this->input->post($fieldName);

		if(isset($fieldValue) && !empty($fieldValue))

		{

			return $fieldValue;

		}

		else

		{

			if($settingData)

			{

				return $settingData[$fieldName];

			}

			else

			{

				return 1;

			}

		}

	}



	function getSettingImage($id = false)

	{

		//if product image is uploaded, then replace current image with new image

		$input_image = $this->input->post('image');



		if(!isset($input_image) && empty($input_image))

		{

			die('empty image');

		}

				

		$config['upload_path'] = './upload/image/settings';

		$config['allowed_types'] = 'gif|jpg|png';

		$config['max_size']	= '500';

		$config['max_width']  = '1024';

		$config['max_height']  = '768';



		$this->load->library('upload', $config);



		if ( ! $this->upload->do_upload('image'))

		{

			$data = array('error' => $this->upload->display_errors());				

		}

		else

		{

			$data = array('upload_data' => $this->upload->data());			

		}

		return $data;

	}



	/************************************************************************

	 * End Settings section

	************************************************************************/



	/************************************************************************

	 * News section

	************************************************************************/



	public function news()

	{

		$data['news'] = $this->News->getAll();

		$data['categories']	= $this->NewsCategory->getAll();
 
		$data['last_id'] = $this->News->getLastID();

		$this->showHeader();

		$this->load->view('admin/news',$data);

		$this->load->view('admin/footer');		

	}



	public function addNewCategory()

	{

		if(isset($_POST['submitBtn']) && !empty($_POST['submitBtn']))

		{

			$data = array(

					'category' => $this->getNewsFieldValue('category'),

					'sub_category' => $this->getNewsFieldValue('sub_category'),

				);

			$this->NewsCategory->addNewCategory($data);

			redirect('admin/news','refresh');

		}

		else

		{

			$this->showHeader();

			$this->load->view('admin/addnewscategory');

			$this->load->view('admin/footer');

		}

	}



	public function addNew()

	{

		if(isset($_POST['submitBtn']) && !empty($_POST['submitBtn']))

		{

			$image = $this->getNewImage();

			$data = array(

					'title' => $this->getNewsFieldValue('title'),

					'image' => $image['upload_data']['file_name'],

					'description' => $this->getNewsFieldValue('description'),

					'category_id' => $this->getNewsFieldValue('category_id'),

				);

			$this->News->addNew($data);

			redirect('admin/news','refresh');

		}

		else

		{

			$data['categories'] = $this->NewsCategory->getAll();

			$this->showHeader();

			$this->load->view('admin/addNews',$data);

			$this->load->view('admin/footer');

		}

	}



	function getNewsFieldValue($fieldName = false, $newsData = false)

	{

		$fieldValue = $this->input->post($fieldName);

		if(isset($fieldValue) && !empty($fieldValue))

		{

			return $fieldValue;

		}

		else

		{

			if($newsData)

			{

				return $newsData[$fieldName];

			}

			else

			{

				return 1;

			}

		}

	}



	function getNewImage($id = false)

	{

		//if product image is uploaded, then replace current image with new image

		$input_image = $this->input->post('image');



		if(!isset($input_image) && empty($input_image))

		{

			die('empty image');

		}

				

		$config['upload_path'] = './upload/image/news';

		$config['allowed_types'] = 'gif|jpg|png';

		$config['max_size']	= '500';

		$config['max_width']  = '1024';

		$config['max_height']  = '768';



		$this->load->library('upload', $config);



		if ( ! $this->upload->do_upload('image'))

		{

			$data = array('error' => $this->upload->display_errors());				

		}

		else

		{

			$data = array('upload_data' => $this->upload->data());			

		}

		return $data;

	}



	/************************************************************************

	 * Order Section

	 * temporarily disable section

	***********************************************************************/

	public function orders()

	{				

		redirect('admin/products','refresh');

	}



	/************************************************************************

	 * End Order Section

	 * temporarily disable section

	***********************************************************************/



	/************************************************************************

	 * Pages Section	

	***********************************************************************/



	public function pages()

	{

		$this->showHeader();

		$data['pages'] = $this->Page->getAll();

		$this->load->view('admin/pages',$data);

		$this->load->view('admin/footer');

	}



	function addNewPage()

	{

		if(isset($_POST['submitBtn']) && !empty($_POST['submitBtn']))

		{

			$data = array(

					'name' => $this->getPageFieldValue('name'),

					'title' => $this->getPageFieldValue('title'),

					'content' => $this->getPageFieldValue('content'),

					'active' => 1,

				);

			$this->Page->addNewPage($data);

			redirect('admin/pages','refresh');

		}

		else

		{

			$this->showHeader();			

			$this->load->view('admin/addNewPage');

			$this->load->view('admin/footer');

		}

	}



	function editPage($id = false)

	{

		if($id == false)

			redirect('admin/pages','refresh');



		$page_data = $this->Page->getPage($id);



		if(isset($_POST['submitBtn']) && !empty($_POST['submitBtn']))

		{

			$data = array(

					'name' => $this->getPageFieldValue('name',$page_data),

					'title' => $this->getPageFieldValue('title',$page_data),

					'content' => $this->getPageFieldValue('content',$page_data),

					'active' => 1,

				);

			$this->Page->updatePage($data,$id);

			redirect('admin/pages','refresh');

		}

		else

		{

			$data['page'] = $page_data;

			$this->showHeader();

			$this->load->view('admin/editPage',$data);

			$this->load->view('admin/footer');

		}

	}



	function getPageFieldValue($fieldName = false, $pagesData = false)

	{

		$fieldValue = $this->input->post($fieldName);

		if(isset($fieldValue) && !empty($fieldValue))

		{

			return $fieldValue;

		}

		else

		{

			if($pagesData)

			{

				return $pagesData[$fieldName];

			}

			else

			{

				return 1;

			}

		}

	}



	/************************************************************************

	 * End Pages Section	

	***********************************************************************/



	/************************************************************************

	 * Login Section	

	***********************************************************************/



	function show_login()
	{
		// tao du lieu tieu de, ...
		$data['setting'] = $this->Setting->getCompany();

		// du lieu duong dan giao dien
		$data['template'] = $this->template;
		$data['template_path'] = $this->template_path;

		$this->load->view($this->template.'login_view',$data,'refresh');
	}



	function login()
	{
		// tao du lieu tieu de, ...
		$data['setting'] = $this->Setting->getCompany();

		// du lieu duong dan giao dien
		$data['template'] = $this->template;
		$data['template_path'] = $this->template_path;

		$this->load->model('User');

		//load library form validation

     	$this->load->library('form_validation');

     	//

     	$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');

     	$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');



     	if($this->form_validation->run() == FALSE)
     	{

     		//Field validation failed.  User redirected to login page

     		$this->load->view($this->template.'login_view',$data);
     	}

     	else
     	{
     		//Go to private area

     		redirect('admin/index', 'refresh');

     	}

	}


	// thoat tai khoan
	function logout()
	{
		 $this->session->unset_userdata('logged_in');

		 session_start();	// add patch fix error [Trying to destroy uninitialized session]
		 session_destroy();		 

		 redirect('admin/show_login', 'refresh');
	}





 	function check_database($password)

	 {

	   //Field validation succeeded.  Validate against database

	   $username = $this->input->post('username');



	   //query the database

	   $result = $this->User->login($username, $password);



	   if($result)

	   {

	     $sess_array = array();

	     foreach($result as $row)

	     {

	       $sess_array = array(

	         'id' => $row->id,

	         'username' => $row->username

	       );

	       $this->session->set_userdata('logged_in', $sess_array);

	     }

	     return TRUE;

	   }

	   else

	   {

	     $this->form_validation->set_message('check_database', 'Invalid username or password');

	     return false;

	   }

	 }



	/************************************************************************

	 * End Login Section	

	***********************************************************************/



	/************************************************************************

	 * End News section

	************************************************************************/

	function getAdminTopPageData()
	{
		$toppage_data = array();

		$toppage_data['num_of_products'] = 10;

		$toppage_data['message'] = 10;

		$toppage_data['stat_count'] = 10000;			

		return $toppage_data;
	}

	

	function onlinesupport()
	{
		$data['support'] = $this->Support->getAll();

		$this->showHeader();

		$this->load->view('admin/onlinesupport',$data);

		$this->load->view('admin/footer');
	}	


	function newsupport()
	{		
		$this->showHeader();

		$this->load->view('admin/onlinesupport',$data);

		$this->load->view('admin/footer');
	}


	// back to previous page
	function back()
	{
		redirect($_SERVER['HTTP_REFERER']);
	}


 }